package com.jlc.book.shop.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jlc.book.shop.delegate.UserDelegate;
import com.jlc.book.shop.to.UserTO;
import com.jlc.book.shop.validator.JLCDataValidator;

public class ChangePasswordAction {

	public String changePassword(HttpServletRequest request,
			HttpServletResponse response) {
		
		String page="changePasswordDef.jsp";
		
		String newpass=request.getParameter("newpass");
		String currpass=request.getParameter("currpass");
		String confpass=request.getParameter("confpass");
		
		boolean compareEquals=true;
		boolean intractWithDB=true;
		
		if(!JLCDataValidator.validateRequired(newpass))
		{
			request.setAttribute("newpass", "New password is required");
			intractWithDB=false;
			compareEquals=false;
		}
		else if(!JLCDataValidator.minLength(newpass, 6))
		{
			
			request.setAttribute("newpass", "New Password must be minimum 6 charcter long");
			intractWithDB=false;
			compareEquals=false;
		}
		else if(!JLCDataValidator.maxLength(newpass, 15))
		{
			
			request.setAttribute("newpass", "New Password must be maximum 15 charcter long");
			intractWithDB=false;
			compareEquals=false;
		}
		
		if(!JLCDataValidator.validateRequired(currpass))
		{
			request.setAttribute("currpass", "Current password is required");
			intractWithDB=false;
			compareEquals=false;
		}
		
		
		if(!JLCDataValidator.validateRequired(confpass))
		{
			request.setAttribute("confpass", "Confirm password is required");
			intractWithDB=false;
			compareEquals=false;
		}
		else if(!JLCDataValidator.minLength(confpass, 6))
		{
			
			request.setAttribute("confpass", "Confirm Password must be minimum 6 charcter long");
			intractWithDB=false;
			compareEquals=false;
		}
		else if(!JLCDataValidator.maxLength(confpass, 15))
		{
			
			request.setAttribute("confpass", "Confirm Password must be maximum 15 charcter long");
			intractWithDB=false;
			compareEquals=false;
		}
		
		if(compareEquals)
		{
			if(!newpass.equals(confpass))
			{
				intractWithDB=false;
				request.setAttribute("changePasswordError", "New & Confirm Password doesnot match");
			}
		}
		if(intractWithDB)
		{
			Object obj=request.getSession().getAttribute("USER_TO");
			UserTO usto=(UserTO)obj;
			
			if(currpass.equals(usto.getPassword()))
			{
				UserTO uto=UserDelegate.changePassword(usto,newpass);
				if(uto!=null)
				{
				request.getSession().setAttribute("USER_TO", uto);
				request.setAttribute("changePasswordError", "Password updated successfully");
				request.setAttribute("CHANGED_PASSWORD", "OK");
					
				}
				else
				{
			request.setAttribute("changePasswordError", "Error in changing password");
				}
			}
			
			else
			{
				request.setAttribute("changePasswordError", "Current password is invalid");
			}
			
		}
		
		return page;
	}

}
